
<template>
  <div class="probability">
    <div class="affix">
      <el-button type="primary" @click="showCorrect = !showCorrect">{{ `${showCorrect ? '隐藏' : '显示'}` }} 参考解析</el-button>
      <el-button v-if="collectIdList.length" type="primary" @click="openCollectHandle"> 我的 ✿ </el-button>
    </div>
    <div v-for="( item, index) in list" :ref="`item${index}`" >
      <RadioGroup v-if="item.question_style === 1" 
        :collectIdList="collectIdList" 
        :showCorrect="showCorrect" 
        collectShow 
        :item="item" 
        :index="index" 
        @addCollect="addCollect"
        @change="(value) => radioChange(value, item)"/>

      <CheckboxGroup v-else-if="item.question_style === 3" 
      :collectIdList="collectIdList" 
      collectShow 
      :item="item" 
      :index="index" 
      @addCollect="addCollect"
      @change="(value) => checkboxChange(value, item)"/>
      
      <!-- <h2><SupportIcon /> 简答题</h2> -->
      <div v-else class="margin-b-15">
        <p class="font-700 title">
          {{ index+1 }}.{{item.title}}
          <img :src="item.title_thumb" />
          （{{item.fraction}}分）
          <span :class="['collect-icon', collectIdList.includes(item.question_id) ? 'red' : '']" 
            title="收藏" 
            @click="addCollect(item.question_id)"
            >✿</span>
        </p>
        <p v-if="showCorrect">
          参考解析：<span>{{item.analysis}}</span>
          <span v-if="!item.analysis"><img :src="item.analyze_thumb" /></span>
        </p>
      </div>
    </div>

    <br/>
    <div class="save-btn">
      <el-button type="success" @click="HandleRest(3)"> 重 做 </el-button>
      <el-button type="primary" @click="saveHandle"> 提 交 </el-button>
    </div>

    <div v-if="dialogVisible">
      <Dialog v-model="dialogVisible" :list="dialogList" :collectIdList="collectIdList" :dialogType="dialogType" @addCollect="addCollect"/>
    </div>
  </div>
  
</template>

<script setup lang="ts">
import { ref, onMounted, getCurrentInstance } from "vue";
import RadioGroup from "./components/RadioGroup.vue";
import CheckboxGroup from "./components/CheckboxGroup.vue";
import Dialog from "./components/Dialog.vue";
import getData from '@/data/util.ts'
import data from '@/data/data414.ts'

import {
  ElButton,
  ElDialog,
  ElMessage
} from "element-plus";

const instance = (getCurrentInstance()) as any; // instance 相当于以前的 `this`

let list =  ref<any[]>([])

let showCorrect = ref<boolean>(true) //显示参考答案

// 收藏列表ID
let collectIdList = ref<string[]>([])

// 错题列表
let errorIds = ref<string[]>([])

//弹窗列表
let dialogType = ref< 0 | 1 | 2>(0) // 0默认 1错误  2收藏
let dialogList = ref<any[]>([])
let dialogVisible = ref<boolean>(false)

onMounted(() => { 
  list.value = getData(data)

  let cIds = localStorage.getItem('collectIdList') 
  if (cIds) { 
    collectIdList.value = JSON.parse(cIds)
  }
})

function checkboxChange(value: [], item: any) { 
  item.error = value.sort().join() !== item.correct_item.sort().join()
  //错题加入错题列表
  item.error && !errorIds.value.includes(item.question_id) && errorIds.value.push(item.question_id)
}
function radioChange(value: string, item: any) { 
  item.error = value && item.correct_item !== item.val
  //错题加入错题列表
  item.error && !errorIds.value.includes(item.question_id) && errorIds.value.push(item.question_id)
}

//提交
function saveHandle() { 
  const emptyIndex = verifyHasEmpty(list.value)
  if (emptyIndex > -1) { 
    scrollIntoRef(emptyIndex) // 滚动到空题
    return false
  }
  dialogType.value = 1
  dialogList.value = getData(data).filter(item => errorIds.value.includes(item.question_id))
  dialogVisible.value = true
}

//打开收藏列表
function openCollectHandle() {
  dialogList.value = []
  dialogType.value = 2
  getData(data).forEach(item => {
    if (collectIdList.value.includes(item.question_id)) { 
      dialogList.value.push(item)
    }
    if (item.child && item.child.length) { 
      item.child.forEach((c: any) => { 
        if (collectIdList.value.includes(c.question_id)) { 
          dialogList.value.push(c)
        }
      })
    }
  })
  dialogVisible.value = true
}

function scrollIntoRef(index: number) {
  instance.refs[`item${index}`][0].scrollIntoView({ behavior: 'smooth' });
}

function verifyHasEmpty(list: any) {
  const empty = list.findIndex((item: any) => { 
    if (
      (item.question_style === 3 && item.val.length === 0) || //多选
      (item.question_style === 1 && !item.val)   // 单选
    ){ 
      return true
    }
  })
  if (empty > -1) { 
    ElMessage({
      message: '存在空题',
      type: 'error',
      plain: true,
    })
    return empty
  }
  return -1
}

type ResetType = 2 | 3 // 2 错题重置   3 列表重置
function HandleRest(type: ResetType) {
   list.value.forEach(item => { 
      item.val = item.question_style === 3 ? [] : ''
      item.error = false
    })

  scrollIntoRef(0)
}

//加入收藏列表
function addCollect(id: string) { 
  if (collectIdList.value.includes(id)) {
    collectIdList.value = collectIdList.value.filter(cid => cid !== id)
  } else { 
    collectIdList.value.push(id)
  }

  localStorage.setItem('collectIdList', JSON.stringify(collectIdList.value))
}

</script>


<style scoped>
h4{
  font-weight: 700;
}
</style>
